package com.rtu.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by ljf on 2018/3/5.
 */
public class MD5Utils {
    private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
            'e', 'f' };

    private static final String _salt = "rtu123";

    static ThreadLocal<MessageDigest> md5 = new ThreadLocal<MessageDigest>();

    public static String MD5(String s) throws NoSuchAlgorithmException {
        if (md5.get() == null)
            md5.set(MessageDigest.getInstance("MD5"));
        md5.get().update(s.getBytes());
        byte[] digest = md5.get().digest();
        return getFormattedText(digest);
    }

    public static String getFormattedText(byte[] bytes) {
        final StringBuilder buf = new StringBuilder(bytes.length * 2);
        for (int j = 0; j < bytes.length; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        return buf.toString();
    }

    public static String MD5(String name, String pwd) throws NoSuchAlgorithmException {
        StringBuilder key = new StringBuilder();
        key.append(name).append(_salt).append(pwd);
        return MD5(key.toString());
    }

    public static void main(String[] args) throws NoSuchAlgorithmException{
        //52bf5a7ec15130808c94dc9a0fb7dfa2
        System.out.println(MD5Utils.MD5("admin"));
    }
}
